package middleware

import (
	"gitee.com/hexug/vblog/tree/master/api/apps/user/impl"
	"github.com/gin-gonic/gin"
	"net/http"
)

func MidAuth(context *gin.Context) {
	username, err := context.Cookie("user")
	if err != nil {
		context.JSON(http.StatusUnauthorized, gin.H{
			"Code": http.StatusUnauthorized,
			"Msg":  err.Error(),
		})
		context.Abort()
		return
	}
	session, err := context.Cookie("uid")
	if err != nil {
		context.JSON(http.StatusUnauthorized, gin.H{
			"Code": http.StatusUnauthorized,
			"Msg":  err.Error(),
		})
		context.Abort()
		return
	}
	if v, ok := impl.Sessions.Load(username); ok {
		if v == session {
			context.Next()
			return
		}
	}
	context.JSON(http.StatusUnauthorized, gin.H{
		"Code": http.StatusUnauthorized,
		"Msg":  "认证失败",
	})
	context.Abort()
	return
}
